package com.zzy.config;

import com.mysql.jdbc.StringUtils;
import com.zzy.pojo.Configuration;
import com.zzy.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

import static com.zzy.pojo.MappedStatement.SqlCommandType.*;


/**
 * 文件描述: <br>
 * 版权所有: Copyright (c) 2021/5/1<br>
 * 完成日期: 2021/5/1<br>
 *
 * @author zainzhang
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        list.addAll(rootElement.selectNodes("//update"));
        list.addAll(rootElement.selectNodes("//insert"));
        list.addAll(rootElement.selectNodes("//delete"));
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            MappedStatement statement = new MappedStatement();
            switch (element.getName()) {
                case "select":
                    statement.setSqlCommandType(SELECT);
                    break;
                case "update":
                    statement.setSqlCommandType(UPDATE);
                    break;
                case "insert":
                    statement.setSqlCommandType(INSERT);
                    break;
                case "delete":
                    statement.setSqlCommandType(DELETE);
                    break;
                default:break;
            }
            statement.setId(id);
            if (!StringUtils.isNullOrEmpty(resultType)) {
                statement.setResultType(Class.forName(resultType));
            }
            if (!StringUtils.isNullOrEmpty(parameterType)) {
                statement.setParameterType(Class.forName(parameterType));
            }
            statement.setBindSql(sql);
            configuration.getMapperStatementMap().put(namespace + "." + id, statement);
        }
    }
}
